package edu.fdzc.learn.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.fdzc.learn.entity.ExamQuestion;
import edu.fdzc.learn.entity.ExamSubmission;
import edu.fdzc.learn.entity.UserAnswer;
import edu.fdzc.learn.entity.vo.ExamResultVO;
import edu.fdzc.learn.entity.vo.ExamSubmissionVO;

import edu.fdzc.learn.mapper.ExamMapper;
import edu.fdzc.learn.mapper.ExamQuestionMapper;
import edu.fdzc.learn.mapper.ExamSubmissionMapper;
import edu.fdzc.learn.service.ExamQuestionService;
import edu.fdzc.learn.service.ExamSubmissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ExamSubmissionServiceImpl extends ServiceImpl<ExamSubmissionMapper, ExamSubmission> implements ExamSubmissionService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamQuestionMapper questionMapper;

    @Autowired
    private ExamQuestionService questionService;

    @Override
    @Transactional
    public Long submitExam(ExamSubmissionVO submissionVO) {
        // 参数校验
        if (submissionVO == null || submissionVO.getExamId() == null ||
                submissionVO.getId() == null || submissionVO.getAnswers() == null) {
            throw new IllegalArgumentException("考试提交信息不完整");
        }

        // 1. 创建提交记录
        ExamSubmission submission = new ExamSubmission();
        submission.setExamId(submissionVO.getExamId());
        submission.setId(submissionVO.getId());
        submission.setAnswers(submissionVO.getAnswers());
        submission.setSubmittedAt(LocalDateTime.now());

        // 2. 保存提交记录
        if (!this.save(submission)) {
            throw new RuntimeException("保存提交记录失败");
        }

        // 3. 计算分数
        Integer score = calculateScore(submissionVO.getExamId(), parseAnswers(submissionVO.getAnswers()));
        submission.setScore(score);
        if (!this.updateById(submission)) {
            throw new RuntimeException("更新分数失败");
        }

        return submission.getId();
    }

    @Override
    public ExamResultVO getExamResult(Long submissionId) {
        // 参数校验
        if (submissionId == null) {
            throw new IllegalArgumentException("提交ID不能为空");
        }

        // 查询提交记录
        ExamSubmission submission = getSubmissionById(submissionId);
        if (submission == null) {
            throw new RuntimeException("考试提交记录不存在");
        }

        // 构建结果VO
        ExamResultVO resultVO = new ExamResultVO();
        resultVO.setSubmissionId(submission.getId());
        resultVO.setExamId(submission.getExamId());
        resultVO.setId(submission.getId());
        resultVO.setScore(submission.getScore());
        resultVO.setSubmittedAt(submission.getSubmittedAt());

        // 获取考试标题
        String examTitle = examMapper.getTitleById(submission.getExamId());
        resultVO.setExamTitle(examTitle);

        return resultVO;
    }

    @Override
    public Integer calculateScore(Long examId, List<UserAnswer> userAnswers) {
        // 参数校验
        if (examId == null || userAnswers == null || userAnswers.isEmpty()) {
            return 0;
        }

        // 获取考试的所有题目及正确答案
        List<ExamQuestion> questions = questionService.getQuestionsByExamId(examId);
        if (questions == null || questions.isEmpty()) {
            return 0;
        }

        // 将题目ID和正确答案映射为Map，方便快速查找
        Map<Long, String> correctAnswers = questions.stream()
                .collect(Collectors.toMap(
                        ExamQuestion::getId,
                        ExamQuestion::getCorrectAnswer
                ));

        // 将题目ID和分数映射为Map，方便快速查找
        Map<Long, Integer> questionScores = questions.stream()
                .collect(Collectors.toMap(
                        ExamQuestion::getId,
                        ExamQuestion::getScore
                ));

        // 计算得分
        int totalScore = 0;
        for (UserAnswer answer : userAnswers) {
            String correctAnswer = correctAnswers.get(answer.getQuestionId());
            if (correctAnswer != null && correctAnswer.equals(answer.getUserAnswer())) {
                // 找到对应题目且答案正确，获取该题分数并累加
                totalScore += questionScores.getOrDefault(answer.getQuestionId(), 0);
            }
        }

        return totalScore;
    }

    @Override
    public ExamSubmission getSubmissionById(Long submissionId) {
        return baseMapper.selectById(submissionId);
    }

    // 解析答案的方法，需要根据实际情况实现
    private List<UserAnswer> parseAnswers(String answers) {
        // 这里只是示例，需要根据实际的 JSON 格式解析
        return new ArrayList<>();
    }
}